package com.xingongchang.baolebei.activity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;

import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;
import com.external.androidquery.callback.AjaxStatus;
import com.external.maxwin.view.XListView;
import com.insthub.BeeFramework.activity.BaseActivity;
import com.insthub.BeeFramework.model.BusinessResponse;
import com.insthub.BeeFramework.view.ToastView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.xingongchang.baolebei.BaolebeiApp;
import com.xingongchang.baolebei.R;
import com.xingongchang.baolebei.adapter.TopicCommentAdapter;
import com.xingongchang.baolebei.fragment.BitmapUtils;
import com.xingongchang.baolebei.model.ProtocolConst;
import com.xingongchang.baolebei.model.UserInfoModel;
import com.xingongchang.baolebei.protocol.PAGINATED;
import com.xingongchang.baolebei.protocol.RECOMMEND_GOODS;
import com.xingongchang.baolebei.protocol.SESSION;
import com.xingongchang.baolebei.protocol.TOPIC_COMMENT;
import com.xingongchang.baolebei.protocol.TOPIC_DETAIL;
import com.xingongchang.baolebei.protocol.USER_INFO;

/**
 * 详细页面
 * 
 * @author haha
 * 
 */
public class TopicDetailActivity extends BaseActivity implements
		BusinessResponse, XListView.IXListViewListener
{

	private ImageView backButton;
	private TextView title;
	private EditText body;
	private ImageView btn_post;
	private UserInfoModel mUserInfoModel;
	private TextView topic_title;
	private TextView topic_body;
	private TextView datetime;
	private ImageView user_photo;
	private ImageView btn_msg;
	private TextView user_name;
	private GridView gridview;
	private LinearLayout layout_recommend;
	public GoodsAdapter goodsAdapter;
	private LinearLayout photos;
	private ImageLoader imageLoader = ImageLoader.getInstance();
	public int screenwidth;
	private XListView xlistView;
	private boolean isSetAdapter = true;
	private TopicCommentAdapter mTopicCommentAdapter;
	int topicId = 0;
	private View view;
	private SharedPreferences shared;
	private SharedPreferences.Editor editor;
	private String uid;
	private Boolean boolean1 = false;
	private ImageView update_btu;
	Bitmap bitmap;
	NetworkInfo mNetworkInfo;// 判断网络是否连接
	NetworkInfo mobNetInfo;
	NetworkInfo wifiNetInfo;
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_topic_detail);
		findViewById();
		setListener();
		mUserInfoModel = new UserInfoModel(this);
		mUserInfoModel.addResponseListener(this);
		topicId = getIntent().getIntExtra("topicid", 0);
		mUserInfoModel.getTopicDetails(topicId);
		mUserInfoModel.getTopicComment(topicId);
		// 判断是否连接网络
		ConnectivityManager mConnectivityManager = (ConnectivityManager) TopicDetailActivity.this
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		mobNetInfo = mConnectivityManager
				.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
		wifiNetInfo = mConnectivityManager
				.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
		if (mNetworkInfo == null)
		{
				ToastView toast = new ToastView(this, "网络异常，请检查网络设置");
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
		}
		initView();
		backButton.setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				finish();
			}
		});
	}

	private void findViewById()
	{
		imageLoader.init(ImageLoaderConfiguration.createDefault(this));
		backButton = (ImageView) findViewById(R.id.top_view_back);
		title = (TextView) findViewById(R.id.top_view_text);
		// btn_share = (ImageView) findViewById(R.id.btn_share);
		body = (EditText) findViewById(R.id.body);
		btn_post = (ImageView) findViewById(R.id.btn_post);
		update_btu = (ImageView) findViewById(R.id.update_btu);
		xlistView = (XListView) findViewById(R.id.comment_list);

		view = LayoutInflater.from(this).inflate(
				R.layout.topic_detail_header_view, null);
		topic_title = (TextView) view.findViewById(R.id.topic_title);
		topic_body = (TextView) view.findViewById(R.id.topic_body);
		datetime = (TextView) view.findViewById(R.id.datetime);
		user_photo = (ImageView) view.findViewById(R.id.user_photo);
		user_name = (TextView) view.findViewById(R.id.user_name);
		gridview = (GridView) view.findViewById(R.id.gridview);
		photos = (LinearLayout) view.findViewById(R.id.photos);
		layout_recommend = (LinearLayout) view
				.findViewById(R.id.layout_recommend);
		btn_msg = (ImageView) view.findViewById(R.id.btn_msg);

		// 输入框限制输入字数
		body.addTextChangedListener(new TextWatcher()
		{
			private CharSequence temp;
			private int selectionStart;
			private int selectionEnd;

			@Override
			public void beforeTextChanged(CharSequence s, int arg1, int arg2,
					int arg3)
			{
				temp = s;
			}

			@Override
			public void onTextChanged(CharSequence s, int arg1, int arg2,
					int arg3)
			{
			}

			@Override
			public void afterTextChanged(Editable s)
			{
				selectionStart = body.getSelectionStart();
				selectionEnd = body.getSelectionEnd();
				if (temp.length() > 120)
				{
					Toast.makeText(TopicDetailActivity.this, "文字不能超出120字",
							Toast.LENGTH_SHORT).show();
					s.delete(selectionStart - 1, selectionEnd);
					int tempSelection = selectionStart;
					body.setText(s);
					body.setSelection(tempSelection);
				}
			}

		});
	}

	private void setListener()
	{
		btn_msg.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View arg0)
			{
				// TODO Auto-generated method stub

				uid = shared.getString("uid", "");
				if (uid.equals(""))
				{
					Intent intent = new Intent(TopicDetailActivity.this,
							SigninActivity.class);
					startActivity(intent);
					overridePendingTransition(R.anim.push_buttom_in,
							R.anim.push_buttom_out);
				} else
				{

					SESSION session = SESSION.getInstance();
					TOPIC_DETAIL topicdetail = mUserInfoModel.topicDetail;
					if (!session.uid.equals(topicdetail.user_id + ""))
					{
						Intent intent = new Intent(TopicDetailActivity.this,
								LetterDetailActivity.class);
						intent.putExtra("receiver", topicdetail.user_id);
						intent.putExtra("username", topicdetail.username);
						startActivity(intent);
					} else
					{
						ToastView toast = new ToastView(
								TopicDetailActivity.this, "不能自己给自己发私信");
						toast.setGravity(Gravity.CENTER, 0, 0);
						toast.show();
					}
				}

			}
		});

		btn_post.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View arg0)
			{
				// TODO Auto-generated method stub
				uid = shared.getString("uid", "");
				if (uid.equals(""))
				{
					Intent intent = new Intent(TopicDetailActivity.this,
							SigninActivity.class);
					startActivity(intent);
					overridePendingTransition(R.anim.push_buttom_in,
							R.anim.push_buttom_out);
				} else
				{

					String bodyinfo = body.getText().toString().trim();
					if (bodyinfo.equals(""))
					{
						Toast.makeText(TopicDetailActivity.this, "评论内容不能为空",
								Toast.LENGTH_SHORT).show();
						return;
					}
					mUserInfoModel.getTopicReply(topicId, bodyinfo);

				}

			}
		});

	}

	private void initView()
	{
		shared = getSharedPreferences("userInfo", 0);
		editor = shared.edit();
		backButton.setVisibility(View.VISIBLE);
		title.setText("帖子详情");
		xlistView.setPullLoadEnable(true);
		xlistView.setRefreshTime();
		xlistView.setXListViewListener(this, 1);
		xlistView.addHeaderView(view);
		xlistView.setFooterDividersEnabled(false);
		xlistView.setOnItemClickListener(new OnItemClickListener()
		{

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3)
			{
				if (position != 1)
				{
					TOPIC_COMMENT comment = mUserInfoModel.commentList
							.get(position - 2);
					SESSION session = SESSION.getInstance();
					if (!session.uid.equals(comment.userid + ""))
					{

						int receiver = comment.userid;
						String username = comment.username;
						Intent intent = new Intent(TopicDetailActivity.this,
								LetterDetailActivity.class);
						intent.putExtra("receiver", receiver);
						intent.putExtra("username", username);
						startActivity(intent);
					}

				}
			}
		});
		// mUserInfoModel.getTopicDetails(topicId);
		// mUserInfoModel.getTopicComment(topicId);

	}

	private void sendData()
	{
		USER_INFO userinfo = BaolebeiApp.userinfo;
		TOPIC_COMMENT comment = new TOPIC_COMMENT();
		comment.userid = userinfo.user_id;
		comment.replyid = 0;
		comment.sex = userinfo.sex;
		comment.body = body.getText().toString().trim();

		comment.creaton = getStringDate();
		comment.userphoto = userinfo.user_photo;
		comment.topicid = topicId;
		comment.username = userinfo.nickname;
		mTopicCommentAdapter.list.add(comment);
		mTopicCommentAdapter.notifyDataSetChanged();
		xlistView.setSelection(xlistView.getCount() - 1);
	}

	public String getStringDate()
	{
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateString = formatter.format(currentTime);
		return dateString;
	}

	@Override
	public void OnMessageResponse(String url, JSONObject jo, AjaxStatus status)
			throws JSONException
	{
		// TODO Auto-generated method stub
		if (url.endsWith(ProtocolConst.TOPIC_DETAIL))
		{
			// if (mUserInfoModel.responseStatus.succeed == 1) {
			bannerHeader();
			// }
		} else if (url.endsWith(ProtocolConst.TOPIC_COMMENT))
		{
			xlistView.stopRefresh();
			xlistView.stopLoadMore();
			xlistView.setRefreshTime();
			Log.e("Test", "ssss");
			setContent();
			PAGINATED paginated = PAGINATED.fromJson(jo
					.optJSONObject("paginated"));
			if (0 == paginated.more)
			{
				xlistView.setPullLoadEnable(false);
			} else
			{
				xlistView.setPullLoadEnable(true);
			}
		} else if (url.endsWith(ProtocolConst.TOPIC_REPLY))
		{
			if (mUserInfoModel.responseStatus.succeed == 1)
			{
				sendData();
				ToastView toast = new ToastView(TopicDetailActivity.this,
						"评论发送成功");
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
				body.setText("");
			}
		}
	}

	/**
	 * 浏览图片列表
	 * 
	 * @param topicDetail
	 */
	public void showPhotos(final TOPIC_DETAIL topicDetail)
	{
		int length = topicDetail.imgurl.length;
		photos.removeAllViews();
		final LayoutParams params1 = new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.FILL_PARENT);
		photos.setOrientation(LinearLayout.VERTICAL);
		for (int i = 0; i < length; i++)
		{
			String imgurl = topicDetail.imgurl[i];
			// 显示买家秀图片
			final ImageView imageView = new ImageView(this);
			imageLoader.displayImage(imgurl, imageView, BaolebeiApp.options,
					new ImageLoadingListener()
					{
						@Override
						public void onLoadingStarted(String arg0, View arg1)
						{
						}

						@Override
						public void onLoadingFailed(String arg0, View arg1,
								FailReason arg2)
						{
							imageView
									.setBackgroundResource(R.drawable.default_image);
							imageView.setScaleType(ScaleType.CENTER_CROP);
							photos.addView(imageView, params1);
						}

						@Override
						public void onLoadingComplete(String arg0, View arg1,
								Bitmap arg2)
						{
							int imageWidth = arg2.getWidth();
							int imageHeight = arg2.getHeight();
							int screenwidth = getDisplayMetricsWidth();
							int photoHeight = (int) ((imageHeight * 1.0 / imageWidth) * screenwidth);
							// try {
							bitmap = zoomImg(arg2, screenwidth, photoHeight);
							bitmap = BitmapUtils.compressImage(bitmap);
							imageView.setImageBitmap(bitmap);
							LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
									screenwidth, photoHeight);
							imageView.setLayoutParams(params);
							imageView.setScaleType(ScaleType.CENTER_CROP);
							photos.addView(imageView, params1);
							// } catch (java.lang.OutOfMemoryError e) {
							// e.printStackTrace();
							// }
						}

						@Override
						public void onLoadingCancelled(String arg0, View arg1)
						{
							imageView.setTag(topicDetail.imgurl);
							if (bitmap == null)
							{
								bitmap.recycle(); // 回收图片所占的内存
							}
						}
					});
			photos.invalidate();
		}
	}

	/**
	 * 处理图片
	 * 
	 * @param bm
	 *            所要转换的bitmap
	 * @param newWidth新的宽
	 * @param newHeight新的高
	 * @return 指定宽高的bitmap
	 */
	public static Bitmap zoomImg(Bitmap bm, int newWidth, int newHeight)
	{
		// 获得图片的宽高
		int width = bm.getWidth();
		int height = bm.getHeight();
		// 计算缩放比例
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		// 取得想要缩放的matrix参数
		Matrix matrix = new Matrix();
		matrix.postScale(scaleWidth, scaleHeight);
		// 得到新的图片 www.2cto.com
		Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix,
				true);
		return newbm;
	}

	public class GoodsAdapter extends BaseAdapter
	{

		private LayoutInflater inflater;
		private ArrayList<RECOMMEND_GOODS> goods = new ArrayList<RECOMMEND_GOODS>();

		public GoodsAdapter(Context context,
				ArrayList<RECOMMEND_GOODS> recommendGoods)
		{
			this.inflater = LayoutInflater.from(context);
			this.goods = recommendGoods;
			imageLoader.init(ImageLoaderConfiguration.createDefault(context));
		}

		@Override
		public int getCount()
		{
			return goods.size();
		}

		@Override
		public Object getItem(int position)
		{
			return goods.get(position);
		}

		@Override
		public long getItemId(int position)
		{
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
			ViewHolder holder;
			if (convertView == null)
			{
				holder = new ViewHolder();
				convertView = this.inflater.inflate(R.layout.gooditem, null);
				holder.goods_photo = (ImageView) convertView
						.findViewById(R.id.gooditem_photo);
				holder.goods_name = (TextView) convertView
						.findViewById(R.id.good_desc);
				holder.goods_price = (TextView) convertView
						.findViewById(R.id.shop_price);
				convertView.setTag(holder);
			} else
			{
				holder = (ViewHolder) convertView.getTag();
			}
			RECOMMEND_GOODS good = goods.get(position);
			imageLoader.displayImage(good.goods_thumb, holder.goods_photo,
					BaolebeiApp.options);
			holder.goods_name.setText(good.goods_name);
			holder.goods_price.setText("￥" + good.shop_price);
			return convertView;
		}

		private class ViewHolder
		{
			ImageView goods_photo;
			TextView goods_name;
			TextView goods_price;
		}

	}

	@Override
	public void onRefresh(int id)
	{
		// TODO Auto-generated method stub
		isSetAdapter = true;
		mUserInfoModel.getTopicDetails(topicId);
		mUserInfoModel.getTopicComment(topicId);
	}

	@Override
	public void onLoadMore(int id)
	{
		// TODO Auto-generated method stub
		isSetAdapter = false;
		mUserInfoModel.getTopicCommentMore(topicId);
	}

	public void bannerHeader()
	{
		SESSION session = SESSION.getInstance();
		if (session.uid.equals(mUserInfoModel.topicDetail.user_id + ""))
		{
			update_btu.setVisibility(View.VISIBLE);
			update_btu.setOnClickListener(new OnClickListener()
			{
				@Override
				public void onClick(View arg0)
				{
					Intent intent = new Intent(TopicDetailActivity.this,
							Update_Topic.class);
					intent.putExtra("topic", topicId);
					startActivity(intent);
				}
			});
		}
		topic_title.setText(mUserInfoModel.topicDetail.title);
		topic_body.setText(mUserInfoModel.topicDetail.body);
		datetime.setText(getDateShort(mUserInfoModel.topicDetail.creaton));
		user_name.setText(mUserInfoModel.topicDetail.username);
		imageLoader.displayImage(mUserInfoModel.topicDetail.userphoto,
				user_photo, BaolebeiApp.options);
		if (!"".equals(mUserInfoModel.topicDetail.user_id + ""))
		{
			user_photo.setOnClickListener(new OnClickListener()
			{
				@Override
				public void onClick(View arg0)
				{
					Intent intent = new Intent(TopicDetailActivity.this,
							Userprofile.class);
					intent.putExtra("userid",
							mUserInfoModel.topicDetail.user_id);
					startActivity(intent);
				}
			});
		}
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		screenwidth = dm.widthPixels;
		if (mUserInfoModel.recommendGoods.size() > 0
				&& mUserInfoModel.recommendGoods != null)
		{
			layout_recommend.setVisibility(View.VISIBLE);
			int length = mUserInfoModel.recommendGoods.size();
			int gridviewWidth = (int) ((screenwidth * 2 / 5 + 10) * length + 10);
			int itemWidth = (int) (screenwidth * 2 / 5);
			// 根据屏幕密度和你的数据长度设置gridView的宽度，和每个item的宽度
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
					gridviewWidth, LinearLayout.LayoutParams.WRAP_CONTENT);
			gridview.setLayoutParams(params);
			gridview.setColumnWidth(itemWidth);
			gridview.setHorizontalSpacing(10);
			gridview.setStretchMode(GridView.NO_STRETCH);
			gridview.setNumColumns(length);
			goodsAdapter = new GoodsAdapter(this, mUserInfoModel.recommendGoods);
			gridview.setAdapter(goodsAdapter);
			gridview.setOnItemClickListener(new OnItemClickListener()
			{

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id)
				{
					// TODO Auto-generated method stub
					Intent it = new Intent(TopicDetailActivity.this,
							ProductDetailActivity.class);
					it.putExtra(
							"good_id",
							mUserInfoModel.recommendGoods.get(position).goods_id);
					startActivity(it);
				}
			});

		} else
		{
			layout_recommend.setVisibility(View.GONE);
		}
		if (mUserInfoModel.topicDetail.imgurl.length > 0
				&& mUserInfoModel.topicDetail.imgurl != null)
		{
			photos.setVisibility(View.VISIBLE);
			showPhotos(mUserInfoModel.topicDetail);
		} else
		{
			photos.setVisibility(View.GONE);
		}

	}

	public void setContent()
	{

		if (mUserInfoModel.commentList.size() == 0)
		{
			Log.e("Test", "ssss11wwsss000");
			mTopicCommentAdapter = new TopicCommentAdapter(this,
					mUserInfoModel.commentList);
			xlistView.setAdapter(mTopicCommentAdapter);
		} else
		{
			Log.e("Test", "ssss11");
			if (mTopicCommentAdapter == null)
			{
				Log.e("Test", "ssss11ww");
				mTopicCommentAdapter = new TopicCommentAdapter(this,
						mUserInfoModel.commentList);
				xlistView.setAdapter(mTopicCommentAdapter);
			} else
			{
				if (isSetAdapter == true)
				{
					Log.e("Test", "ssss11wwsss");
					xlistView.setAdapter(mTopicCommentAdapter);
				} else
				{
					mTopicCommentAdapter.list = mUserInfoModel.commentList;
					mTopicCommentAdapter.notifyDataSetChanged();
				}
			}

		}
	}

	@Override
	protected void onDestroy()
	{
		super.onDestroy();
	}

	@Override
	protected void onStop()
	{
		super.onStop();
	}

	// 获取屏幕宽度
	public int getDisplayMetricsWidth()
	{
		int i = getWindowManager().getDefaultDisplay().getWidth();
		int j = getWindowManager().getDefaultDisplay().getHeight();
		return Math.min(i, j);
	}

}
